package com.oj.friend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.oj.common.core.domain.R;
import com.oj.common.core.domain.TableDataInfo;
import com.oj.common.core.enums.ResultCode;
import com.oj.friend.domain.question.Question;
import com.oj.friend.domain.question.es.QuestionES;
import com.oj.friend.domain.question.dto.QuestionQueryDTO;
import com.oj.friend.domain.question.vo.QuestionDetailVO;
import com.oj.friend.domain.question.vo.QuestionVO;
import com.oj.friend.elasticsearch.QuestionRepository;
import com.oj.friend.manager.QuestionCacheManager;
import com.oj.friend.mapper.QuestionMapper;
import com.oj.friend.service.IQuestionService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author bin
 * @Date 2025/6/9
 */
@Service
public class QuestionServiceImpl implements IQuestionService {

    @Resource
    private QuestionRepository questionRepository;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // elasticsearch 使用的Page分页 是来自spring-data的
        long count = questionRepository.count();
        Page<QuestionES> questionESPage;
        System.out.println(count);
        if (count <= 0) {
            refreshQuestion();
        }
        //排序设置
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 分页配置
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        String keyWord = questionQueryDTO.getKeyword();
        Integer difficulty = questionQueryDTO.getDifficulty();
        if (StrUtil.isEmpty(keyWord) && difficulty == null) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyWord)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyWord, keyWord, pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDiffulty(keyWord, keyWord, difficulty, pageable);
        }
        //返回questionVO
        long totalElements = questionESPage.getTotalElements();
        if(totalElements <= 0){
            return TableDataInfo.empty();
        } else {
            List<QuestionES> content = questionESPage.getContent();
            List<QuestionVO> questionVOS = BeanUtil.copyToList(content, QuestionVO.class);
            return TableDataInfo.success(questionVOS, totalElements);
        }
    }

    @Override
    public R<QuestionDetailVO> detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return R.ok(questionDetailVO);
        }
        // questionES为空
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        }
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return R.ok(questionDetailVO);
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        Long id = questionCacheManager.getPreQuestion(questionId);
        // 返回String 类型 防止出现精度问题
        return String.valueOf(id);
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        Long id = questionCacheManager.nextQuestion(questionId);
        // 返回String 类型 防止出现精度问题
        return String.valueOf(id);
    }

    private void refreshQuestion() {
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<>());
        if (CollectionUtil.isEmpty(questions)) {
            return;
        }
//        System.out.println(1111);
        List<QuestionES> questionES = BeanUtil.copyToList(questions, QuestionES.class);
        questionRepository.saveAll(questionES);
    }
}
